package com.ecld.grpc.dao;

import com.ecld.grpc.server.GRpcServer;
import com.ecld.grpc.tool.ConnectionPoolUtils;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AuthDao {

    private static final Logger logger = Logger.getLogger(GRpcServer.class.getName());

    public boolean updateUserDao(String uname,String passwd) throws SQLException {
        String sql = "UPDATE USER SET PASSWD = ? WHERE UNAME = ?";
        logger.log(Level.FINE,"exec SQL {"+sql+"}");
        Connection conn = getConn();
        PreparedStatement st = conn.prepareStatement(sql);
        st.setString(1,passwd);
        st.setString(2,uname);
        st.executeUpdate();
        st.close();
        conn.close();
        return true;
    }

    public String getUserPasswdDao(String uname) throws SQLException {
        String sql = "SELECT PASSWD FROM USER WHERE UNAME =?";
        logger.log(Level.FINE,"exec SQL {"+sql+"}");
        Connection conn = getConn();
        PreparedStatement st = conn.prepareStatement(sql);
        st.setString(1,uname);
        ResultSet rs = st.executeQuery();
        rs.next();
        String passwd = rs.getString("PASSWD");
        rs.close();
        st.close();
        conn.close();
        return passwd;
    }

    public String getTokenDao(String uname) throws SQLException {
        String sql = "SELECT TOKEN,VALID_UNTIL FROM USER WHERE UNAME = ?";
        logger.log(Level.FINE,"exec SQL {"+sql+"}");
        Connection conn = getConn();
        PreparedStatement st = conn.prepareStatement(sql);
        st.setString(1,uname);
        ResultSet rs = st.executeQuery();
        rs.next();
        String token = rs.getString("TOKEN");
        rs.close();
        st.close();
        conn.close();
        return token;
    }

    public long getTokenUntilDao(String uname) throws SQLException {
        String sql = "SELECT VALID_UNTIL FROM USER WHERE UNAME =?";
        logger.log(Level.FINE,"exec SQL {"+sql+"}");
        Connection conn = getConn();
        PreparedStatement st = conn.prepareStatement(sql);
        st.setString(1,uname);
        ResultSet rs = st.executeQuery();
        rs.next();
        long valid_until = rs.getLong("VALID_UNTIL");
        rs.close();
        st.close();
        conn.close();
        return valid_until;
    }

    public boolean setTokenDao(String uname,long valid_until,String token) throws SQLException {
        String sql = "UPDATE USER SET TOKEN = ? , VALID_UNTIL = ? WHERE UNAME = ?";
        logger.log(Level.FINE,"exec SQL {"+sql+"}");
        Connection conn = getConn();
        PreparedStatement st = conn.prepareStatement(sql);
        st.setString(1,token);
        st.setLong(2,valid_until);
        st.setString(3,uname);
        st.executeUpdate();
        st.close();
        conn.close();
        return true;
    }

    public Connection getConn() {
        return ConnectionPoolUtils.getInstance().getConnection();
    }
}